<?php
namespace app\middleware;

use app\admin\Auth;
use app\model\AdminModel;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

/**
 * 后台模块中间件
 */
class Admin implements MiddlewareInterface
{
    public function process(Request $request, callable $next) : Response
    {
        $controller = $request->controller;
        $action = $request->action;
        $app = $request->app;

        if ($controller != 'app\admin\controller\PublicController') {

            //管理员鉴权,验证登录、权限
            $admin_id = get_admin_id();
            if (empty($admin_id)) {

                if ($request->expectsJson()) {
                    return error('请先登录', '', [], 10001);
                }
                return redirect('/admin/public/login');
            }
            $admin = AdminModel::find($admin_id);
            if($admin['status'] != '1'){
                $request->session()->delete('admin_id');
                return error('账号被禁用');
            }

            //权限验证
            if (!Auth::canAccess($admin_id, $controller, $action, $app)) {
                return error('没有访问权限!');
            }
        }

        return $next($request);
    }
    
}
